﻿using System.Windows;

namespace SHomeWorkshop.LunarPresentation.Commands
{
    public partial class Command
    {
        public static void CutOrDeleteLeaf(bool OnlyDelete = true)
        {
            if (Globals.selectedEditor == null) return;
            if (Globals.selectedEditor.SelectedExpression == null) return;

            LunarPresentation.Expressions.Expression curEx
                = Globals.selectedEditor.SelectedExpression;

            if (curEx is Expressions.LeafPanel == false)
            {
                MessageBox.Show("请先选中一个叶面板！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            Expressions.LeafPanel leaf = curEx as Expressions.LeafPanel;
            if (leaf.LeafType == Expressions.LeafPanel.LeafPanelType.Root)
            {
                MessageBox.Show("树的叶首面板不允许剪切或删除！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            //删除需要递归。
            if (leaf.ParentExpression == null ||
                leaf.ParentExpression is Expressions.Tree == false)
            {
                MessageBox.Show("发生意外，这个叶面板不在某个树上或被挂接到了某个意外的公式中！"
                    , Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            Expressions.LeafPanel preLevelLeaf = leaf.PreLevelLeaf;

            Expressions.Tree pTree = leaf.ParentExpression as Expressions.Tree;

            ModifingItem mi = new ModifingItem() { OldSelectedExID = leaf.ExID };
            pTree.CutOrDeleteLeaf(leaf, mi, OnlyDelete);

            pTree.Editor.Do(mi);
            pTree.Editor.IsModified = true;

            if (preLevelLeaf != null)
            {
                pTree.Editor.SelectedExpression = preLevelLeaf;
                mi.NewSelectedExID = preLevelLeaf.ExID;
            }
            else
            {
                pTree.Editor.SelectedExpression = pTree;
                mi.NewSelectedExID = pTree.ExID;
            }
        }
    }
}
